# -*- encoding: utf-8 -*-
# author: binux<17175297.hk@gmail.com>

from tornado.web import HTTPError
from tornado.options import options
from .base import BaseHandler

import re
from urllib import quote_plus
from libs.tools import thunder_filename_encode
    
class GetLiXianURLHandler(BaseHandler):
    def get(self):
        str_task_ids = self.get_argument("task_id")
        task_ids = [int(task_id) for task_id in str_task_ids.split(',')]
        referer = self.request.headers.get("referer")
        if referer and not self.request.host in referer[4:10+len(self.request.host)]:
            self.redirect("/share/"+str(str_task_ids))
            return
            
        vip_info = self.get_vip()
        
        tasks = []
        task = None
        for task_id in task_ids:
            task = self.task_manager.get_task(task_id)
            if task is None:
                raise HTTPError(404, "task is not exists.")
                
            tmp_files = self.task_manager.get_file_list(task_id, vip_info)
            if tmp_files is None:
                raise HTTPError(500, "Error when getting file list.") 
                
            tasks.append((task, tmp_files))
     
        cookie = options.cookie_str % vip_info["gdriveid"]
        self.render("lixian.html", tsk=task, tasks=tasks, task_ids=str_task_ids, cookie=cookie, gdriveid=vip_info["gdriveid"])

class ShareHandler(BaseHandler):
    def get(self, task_ids, something):
        str_task_ids = task_ids
        task_ids = [int(task_id) for task_id in task_ids.split(',')]
        
        vip_info = self.get_vip()
        
        tasks = []
        task = None
        for task_id in task_ids:
            task = self.task_manager.get_task(task_id)
            if task is None:
                raise HTTPError(404, "Task not exists.")
                
            tmp_files = self.task_manager.get_file_list(task_id, vip_info)
            if tmp_files is None:
                raise HTTPError(500, "Error when getting file list.") 
                
            tasks.append((task, tmp_files))
     
        cookie = options.cookie_str % vip_info["gdriveid"]
        self.render("share.html", tsk=task, tasks=tasks, task_ids=str_task_ids, cookie=cookie, gdriveid=vip_info["gdriveid"])

class XSSDoneHandler(BaseHandler):
    def get(self):
        gdriveid = self.get_argument("gdriveid")
        cookie = options.cookie_str % gdriveid
        self.write('document.cookie="%s"' % cookie)
        self.set_cookie("xss", gdriveid)

class XSSJSHandler(BaseHandler):
    def get(self):
        render_tpl = "xss.js"

        gdriveid = self.get_vip()["gdriveid"]
        cookie = options.cookie_str % gdriveid
        self.render(render_tpl, cookie=cookie, gdriveid=gdriveid)

class XSSCheckHandler(BaseHandler):
    def get(self):
        gdriveid = self.get_argument("gdriveid")
        self.render("xss_check.js", gdriveid=gdriveid)

lixian_n_re = re.compile(r"&n=\w+")         
class IDMExportHandler(BaseHandler):
    def get(self, task_ids, something):
        index = self.get_argument("i", None)
        
        total_files, gdriveid = export_files(self, task_ids, index)
        
        # self.set_header("Content-Disposition", 'attachment; filename="%s_idm_%s.ef2"' % (options.site_name,hash(task_ids)))
        def rewrite_url(url, filename):
            return lixian_n_re.sub("&n="+thunder_filename_encode(filename), url)

        template = "<\r\n%s\r\ncookie: gdriveid=%s\r\n>\r\n"
        for f in total_files:
            print(f.dirtitle, f.lixian_url)
            if not f.lixian_url:
                continue
            self.write(template % (rewrite_url(f.lixian_url, f.dirtitle), gdriveid))

class aria2cExportHandler(BaseHandler):
    def get(self, task_ids, something):
        index = self.get_argument("i", None)
        
        total_files, gdriveid = export_files(self, task_ids, index)
        
        # self.set_header("Content-Disposition", 'attachment; filename="%s_aria2c_%s.down"' % (options.site_name,hash(task_ids)))
        template = "%s\r\n  out=%s\r\n  header=Cookie: gdriveid=%s\r\n  continue=true\r\n  max-connection-per-server=5\r\n  split=10\r\n  parameterized-uri=true\r\n\r\n"
        for f in total_files:
            if not f.lixian_url:
                continue    
            self.write(template % (f.lixian_url.replace("gdl", "{gdl,dl.f,dl.g,dl.h,dl.i,dl.twin}"), f.dirtitle, gdriveid))

class orbitExportHandler(BaseHandler):
    def get(self, task_ids, something):
        index = self.get_argument("i", None)
        
        total_files, gdriveid = export_files(self, task_ids, index)

        template = "%s|%s||gdriveid=%s\r\n"

        for f in total_files:
            if not f.lixian_url:
                continue
            self.write(template % (f.lixian_url, f.dirtitle.replace("|", "_"), gdriveid))
            
def export_files(handler, task_ids, index):
    print task_ids
    task_ids = task_ids.split(',')
    tasks = {}
    for id in task_ids:
        tasks[int(id)] = []
        
    if index:
        try:
            index = index.split(",")
            for ind in index:
                mark, taskid, file_index = ind.split('-')
                taskid = int(taskid)
                file_index = int(file_index)
                if taskid in tasks:
                    tasks[taskid].append(file_index)
                else:
                    tasks[taskid]=[file_index,]
        except:
            raise HTTPError(403, "Request format error.")
    
    vip_info = handler.get_vip()
    handler.set_header("Content-Type", "application/octet-stream")
    
    
    total_files = []
    for task_id, file_index in tasks.items():
        file_index = set(file_index)
        files = handler.task_manager.get_file_list(task_id, vip_info)
        if files is None:
            raise HTTPError(500, "Error when getting file list.")
        if files == []:
            raise HTTPError(404, "Task not exists.")
        
        if file_index:
            files = (x for i, x in enumerate(files) if i in file_index)
        total_files.extend(files)
          
    return total_files, vip_info["gdriveid"]
    
handlers = [
        (r"/get_lixian_url", GetLiXianURLHandler),
        (r"/export/"+options.site_name+"_idm_(\d+(,\d+)*).*?\.ef2", IDMExportHandler),
        (r"/export/"+options.site_name+"_aria2c_(\d+(,\d+)*).*?\.down", aria2cExportHandler),
        (r"/export/"+options.site_name+"_orbit_(\d+(,\d+)*).*?\.olt", orbitExportHandler),
        (r"/share/(\d+(,\d+)*)", ShareHandler),
        (r"/xss", XSSDoneHandler),
        (r"/xssjs", XSSJSHandler),
]
ui_modules = {
}
